package com.xk.comparator;

import java.util.ArrayList;
import java.util.Comparator;

/**
 * Comparator的使用
 */
public class Test {
    public static void main(String[] args) {
        ArrayList<Teacher> teachers=new ArrayList<>();
        Teacher t1=new Teacher("张三","女",23);
        Teacher t2=new Teacher("李四","男",21);
        Teacher t3=new Teacher("王五","女",19);
        Teacher t4=new Teacher("赵六","男",20);

        teachers.add(t1);
        teachers.add(t2);
        teachers.add(t3);
        teachers.add(t4);

        System.out.println("原始数据：");
        for (Teacher t:teachers){
            System.out.println(t.toString());
        }

        //按年龄排序
        System.out.println("\n按年龄排序");
        teachers.sort(new Comparator<>() {
            @Override
            public int compare(Teacher teacher, Teacher t1) {
                return teacher.getAge() - t1.getAge();
            }
        });
        System.out.println("排序后的结果为：");
        for (Teacher s:teachers){
            System.out.println(s);
        }

        //按性别排序
        System.out.println("\n按性别排序");
        teachers.sort(new Comparator<Teacher>() {
            @Override
            public int compare(Teacher teacher, Teacher t1) {
                if (teacher==null || t1==null){
                    return  -1;
                }

                int num1=teacher.getSex().compareTo(t1.getSex());
                int num2=num1==0?(t1.getAge()-teacher.getAge()):num1;
                return num2;
            }
        });
        System.out.println("按性别排序后的结果为：");
        for (Teacher s:teachers){
            System.out.println(s);
        }
    }
}
